package route

import (
	"DouBan/model"
	"DouBan/utils/logger"
	"github.com/gin-gonic/gin"
	"net/http"
)

func CheckTokenMiddle(isStrict bool) gin.HandlerFunc {
	return func(context *gin.Context) {
		remoteIpString := ""
		if remoteIp, ok := context.RemoteIP(); ok {
			remoteIpString = remoteIp.String()
		}
		url := context.Request.URL.String()
		var infoClaim = new(model.InfoClaim)
		tokenString, err := context.Cookie("token")
		if err != nil {
			if isStrict {
				logger.WarnLn("checkTokenMiddleware", "info", "获取token失败", "requestIp", remoteIpString, "requestUrl", url)
				context.JSON(http.StatusUnauthorized, gin.H{"status": -1, "msg": "非法请求", "data": nil})
				context.Abort()
				return
			} else {
				context.Next()
			}
		} else {
			if infoClaim.ParseJwtToken(tokenString) {
				if msg, ok := infoClaim.CheckJwtToken(); !ok {
					logger.WarnLn("checkTokenMiddleware", "info", msg, "requestIp", remoteIpString, "requestUrl", url)
					context.JSON(http.StatusUnauthorized, gin.H{"status": -1, "msg": msg, "data": nil})
					context.Abort()
					return
				}
			} else {
				logger.WarnLn("checkTokenMiddleware", "info", "token解析失败", "requestIp", remoteIpString, "requestUrl", url)
				context.JSON(http.StatusUnauthorized, gin.H{"status": -1, "msg": "非法请求", "data": nil})
				context.Abort()
				return
			}
			context.Set("infoClaim", infoClaim)
			//todo 如果next里面执行时间过长会导致误差 先用着 有问题再改回context.Writer.Header.Set写法
			context.SetCookie("token", infoClaim.GenerateJwtToken(), 1800, "", "", true, false)
			context.Next()
		}
		logger.DebugLn("debug", "requestIp", remoteIpString, "requestUrl", url)
	}
}
